package com.start.demo.user.service.impl;

import java.util.List;
import java.util.concurrent.TimeUnit;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import com.start.demo.user.controller.Cst;
import com.start.demo.user.dao.UserDao;
import com.start.demo.user.model.User;
import com.start.demo.user.service.UserService;

@Service
public class UserServiceImpl implements UserService {
	private Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);

	@Resource
	private UserDao userDao;

	@Resource
	private RedisTemplate<String, User> template;

	/**
	 * 
	 */
	public boolean addUser(User user) {
		if (null == user) {
			return false;
		}
		if (StringUtils.isBlank(user.getName())) {
			return false;
		}
		boolean result = userDao.insertUser(user) > 0;
		return result;
	}

	/**
	 * 
	 */
	public boolean removeUserById(String id) {
		if (StringUtils.isBlank(id)) {
			return false;
		}
		boolean result = userDao.deleteUserById(id) > 0;
		return result;
	}

	/**
	 * 更新用户信息
	 */
	public boolean modifyUser(User user) {
		if (null == user) {
			return false;
		}
		if (StringUtils.isBlank(user.getId())
				&& StringUtils.isBlank(user.getUserId())) {
			return false;
		}
		user = userDao.getUserById(user.getId());
		if (null == user) {
			return false;
		}
		// 删除缓存
		template.delete(Cst.USER_ID + user.getId());
		return userDao.updateUser(user) > 0;
	}

	/**
	 * 根据用户ID查询用户信息，redis缓存使用
	 */
	public User getUserById(String id) {
		if (StringUtils.isBlank(id)) {
			return null;
		}
		User user;
		// 查找是否存在
		try {

			boolean exist = template.hasKey(Cst.USER_ID + id);
			if (exist) {
				return template.opsForValue().get(Cst.USER_ID + id);
			}
		} catch (Exception e) {
			logger.error("redis error");
		}
		user = userDao.getUserById(id);
		// 设置缓存
		try {
			if (null != user) {

				template.opsForValue().set(Cst.USER_ID + id, user);
				// 设置过期时间
				template.expire(Cst.USER_ID + id, 10, TimeUnit.MINUTES);
			}
		} catch (Exception e) {
			logger.error("redis error");
		}
		return user;
	}

	/**
	 * 
	 */
	public List<User> queryUserList(User user) {
		if (null == user) {
			return null;
		}
		List<User> userList = userDao.selectUserList(user);
		return userList;
	}

}
